package com.util;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.security.PublicKey;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Base64;

public class SSLUtil {
    public static void main(String[] args) throws Exception {
        cer("keys/test/sChat.cer");
        cer("keys/test/cChat.cer");
    }

    // 查看cer证书文件中的公钥
    public static void cer(String cerPath) throws CertificateException, FileNotFoundException {
        System.out.printf("证书：%s： \n", cerPath);
        CertificateFactory fact = CertificateFactory.getInstance("X.509");
        InputStream is = SSLUtil.class.getClassLoader().getResourceAsStream(cerPath);
        X509Certificate certificate = (X509Certificate) fact.generateCertificate(is);
        PublicKey pk = certificate.getPublicKey();
        byte[] pkBytes = pk.getEncoded();
        String hex = Hex.encodeHexString(pkBytes);
        System.out.println("公钥hex：" + hex);
        String pkHex = Base64.getEncoder().encodeToString(pkBytes);
        System.out.println("公钥base64：" + pkHex);
        System.out.println("公钥sha1：" + DigestUtils.sha1Hex(pkBytes));

    }
}
